<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-09 14:27:49
 * @LastEditors: wangming
 * @LastEditTime: 2022-07-27 16:47:29
 * @Description: file content
-->
<template>
  <el-upload
    :drag="drag"
    :multiple="multiple"
    action=""
    :accept="accept"
    :show-file-list="false"
    :http-request="handleHttpRequest"
    :before-upload="beforeUpload"
  >
    <slot></slot>
  </el-upload>
</template>

<script>
import { postImagesUpload } from "@/apis/paas/ImagesController.js";
import { postStaticresourceUpload } from "@/apis/paas/StaticResourceController.js";
import { postFileUpload } from "@/apis/dev-centre/FileController.js";
function toBase64(file) {
  return new Promise((resolve) => {
    var reader = new FileReader();
    reader.onloadend = function () {
      resolve(reader.result);
    };
    if (file) {
      reader.readAsDataURL(file);
    }
  });
}

export default {
  name: "CommonUpload",
  props: {
    beforeUpload: {
      type: Function,
      default: () => {
        return true;
      },
    },
    drag: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    accept: {
      type: String,
      default: "image/jpg,image/jpeg,image/png",
    },
    size: {
      type: Number,
      default: 10,
    },
    base64: {
      type: Boolean,
      default: false,
    },
    client: {
      type: Boolean,
      default: false,
    },
    resourceType: {
      type: String,
      default: () => "",
    },
    isCloud: {
      type: Boolean,
      default: () => false,
    },
  },
  methods: {
    async handleHttpRequest(param) {
      const file = param.file;
      const { size } = this;
      const fileSize = file.size / 1024 / 1024;
      const isLt = fileSize < size;
      if (!isLt) {
        const max = size < 1 ? size * 1000 : size;
        const unit = size < 1 ? "KB" : "MB";
        this.$message.error(`上传大小不能超过 ${max}${unit}`);
        return;
      }
      if (this.base64) {
        toBase64(file).then((res) => {
          this.$emit("success", res);
        });
      } else {
        const formData = new FormData();
        formData.append("file", file);
        let res = "";
        if (this.isCloud) {
          this.resourceType &&
            formData.append("resourceType", this.resourceType);
          res = await postFileUpload(formData);
        } else if (!this.client) {
          res = await postImagesUpload(formData);
        } else {
          res = await postStaticresourceUpload(formData);
        }
        this.$emit("success", res);
        if (this.isCloud) {
          this.$emit("successForName", {
            name: file.name,
            path: res.accessUrl,
          });
        } else {
          this.$emit("successForName", { name: file.name, path: res });
        }
      }
    },
  },
};
</script>

<style></style>
